#!/usr/bin/env node
/**
 * Archive 分支清理脚本
 * 自动清理超过指定天数的 archive 分支
 */

const { exec } = require('../utils/exec');
const { Logger } = require('../utils/logger');
const config = require('../utils/config');

const logger = new Logger('[git:archive]');

/**
 * 清理过期的 archive 分支
 */
function cleanupArchives(daysToKeep = 30, dryRun = false) {
  logger.title(`Archive Branch Management`);
  logger.info(`Retention period: ${daysToKeep} days`);

  if (dryRun) {
    logger.warning('DRY RUN MODE - No branches will be deleted');
  }
  logger.blank();

  // 获取所有 archive 分支及其时间戳
  const result = exec(
    'git for-each-ref --format="%(refname:short)|%(committerdate:unix)" refs/heads/archive/',
    { silent: true }
  );

  if (!result || result.trim() === '') {
    logger.info('No archive branches found.');
    return;
  }

  const now = Date.now() / 1000;
  const cutoffTime = now - daysToKeep * 24 * 60 * 60;

  const branches = result.trim().split('\n');
  let deletedCount = 0;
  let keptCount = 0;

  logger.info('Processing branches:');
  logger.blank();

  branches.forEach((line) => {
    const [branch, timestamp] = line.split('|');
    const branchTime = parseInt(timestamp);
    const date = new Date(branchTime * 1000);
    const ageInDays = Math.floor((now - branchTime) / (24 * 60 * 60));

    const dateStr = date.toLocaleDateString();
    const ageStr = `${ageInDays} days old`;

    if (branchTime < cutoffTime) {
      if (dryRun) {
        logger.warning(`Would delete: ${branch} (${dateStr}, ${ageStr})`);
      } else {
        exec(`git branch -D ${branch}`);
        logger.error(`Deleted: ${branch} (${dateStr}, ${ageStr})`);
      }
      deletedCount++;
    } else {
      logger.success(`Keeping: ${branch} (${dateStr}, ${ageStr})`);
      keptCount++;
    }
  });

  // 总结
  logger.blank();
  logger.title('Summary');
  logger.info(`Total branches: ${branches.length}`);
  logger.info(`To delete: ${deletedCount}`);
  logger.info(`To keep: ${keptCount}`);

  if (!dryRun && deletedCount > 0) {
    logger.blank();
    logger.success('Archive cleanup completed!');
  }
}

// 解析命令行参数
const daysToKeep =
  parseInt(process.argv[2]) || parseInt(config.get('ARCHIVE_RETENTION_DAYS', '30'));
const dryRun = process.argv[3] === 'true';

cleanupArchives(daysToKeep, dryRun);
